<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9_使用$scope处理升降序</title>
    <script src="./lib/angularjs.js"></script>
    <style>
        .bold {
            font-weight: bolder;
        }
    </style>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
    <table border="1px" width="500px">
        <tr class="bold">
            <td ng-click="sorted('id')">编号 <span ng-if="!state.id">升序</span><span ng-if="state.id">降序</span></td>
            <td ng-click="sorted('goods')">商品 <span ng-if="!state.goods">升序</span><span ng-if="state.goods">降序</span>
            </td>
            <td ng-click="sorted('trade')">购买数 <span ng-if="!state.trade">升序</span><span ng-if="state.trade">降序</span>
            </td>
        </tr>
        <tr ng-repeat="(k, v) in data">
            <td>{{v.id}}</td>
            <td>{{v.goods}}</td>
            <td>{{v.trade}}</td>
            <!-- <td ng-bind="v.id"></td>
            <td ng-bind="v.goods"></td>
            <td ng-bind="v.trade"></td> -->
        </tr>
    </table>
</body>
<script>
    const myApp = angular.module("myApp", [])
    myApp.controller("myCtrl", ["$scope", "$filter", function ($scope, $filter) {
        $scope.data = [{ id: 1, goods: "车灯", trade: 33 }, { id: 2, goods: "车门", trade: 44 }, { id: 3, goods: "车镜", trade: 55 }]
        $scope.state = { id: false, goods: false, trade: false }
        $scope.sorted = function (field) {
            // 只排序一列
            for (let item in $scope.state) {
                if (item === field) {
                    console.log(item, field);
                    $scope.state[field] = !$scope.state[field];
                } else {
                    $scope.state[item] = false
                }
            }
            $scope.data = $filter("orderBy")($scope.data, field, $scope.state[field])
        }
    }])
</script>

</html>